﻿using System;
using System.Reflection;
using LazyMapper.Core.Helpers;

namespace LazyMapper.Core
{
    internal class PropertyMappingByProp<TInput, TOutput> : IPropertyMapping<TInput, TOutput>
    {
        private readonly PropertyInfo _inputProp;
        private readonly PropertyInfo _outputProp;
        private readonly MapperInstance _instance;
        private readonly Action<TInput, TOutput> _simpleCopy;

        public PropertyMappingByProp(PropertyInfo inputProp, PropertyInfo outputProp, MapperInstance instance)
        {
            _inputProp = inputProp;
            _outputProp = outputProp;
            _instance = instance;

            if (_inputProp.PropertyType == _outputProp.PropertyType)
            {
                _simpleCopy = ExpressionExtensions.CopyValue<TInput, TOutput>(inputProp, outputProp);
            }
        }

        public void Map(TInput input, TOutput output)
        {
            if (_simpleCopy != null)
            {
                _simpleCopy(input, output);
            }
            else
            {
                // todo: Rolf Optimize
                var value = _inputProp.GetValue(input, null);
                var outputOriginalValue = _outputProp.GetValue(output, null);
                var map = _instance.Map(_inputProp.PropertyType, value, _outputProp.PropertyType, outputOriginalValue);
                _outputProp.SetValue(output, map, null);
            }
        }

        public string MemberName
        {
            get { return _inputProp.Name; }
        }

        public void Map(object input, object output)
        {
            
        }
    }
}